// pages/home-music/index.js
import { rankingStore, rankingMap } from '../../store/index'


import {getBanner, getSongMemu } from '../../service/api_music'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    banners:[],
    swiperHeight:0,   //轮播图组件image的图片的高度
    recommendSongs:[],  //推荐歌曲的数据
    hotSongMenu:[],
    recommendSongMenu:[],
    rankings:{ 0: {}, 2: {}, 3: {} }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 获取页面数据
    this.getPageData()
    // 发起共享数据的请求  dispatch  发送
    rankingStore.dispatch("getRankingDataAction")
    // 从store中获取共享的数据
    //歌曲推荐数据处理
    rankingStore.onState("hotRanking",res=>{
      // console.log("home-music:" ,res);
      if(!res.tracks) return
     const recommendSongs = res.tracks.slice(0,6)
     this.setData({ recommendSongs })  
    })

    rankingStore.onState("newRanking", this. getRankingHandle(0))
    rankingStore.onState("originRanking", this. getRankingHandle(2))
    rankingStore.onState("upRanking", this. getRankingHandle(3))
},

  //网络请求
  getPageData: function(){
    getBanner().then(res=>{
      // console.log(res);
      this.setData({banners:res.banners})
    }),
    getSongMemu().then(res=>{
     this.setData({ hotSongMenu:res.playlists})
    }),
    getSongMemu("华语").then(res=>{
      // console.log(res);
      this.setData({ recommendSongMenu:res.playlists})
     })
    
  },
 
  //处理首页搜索框点击跳转搜索框事件
  handleSearchClick: function(){
    wx.navigateTo({
      url: '../detail-search/index',
    })
  },

  //处理轮播图高度的事件
  handleSwiperImageLoaded: function(){
  //  这里的bindload的handleSwiperImageLoaded拿到的宽高是原本图片的宽高，我们需要的是组件里面图片的高
  //获取轮播图加载完成时组件图片的高度  
  const query = wx.createSelectorQuery()
  query.select('.swiper-image').boundingClientRect()
  query.exec((res)=>{
    const rect = res[0]
    // console.log(rect.height)
    this.setData({ swiperHeight: rect.height })
})
  },

  // 推荐歌曲点击事件
  handleMoreClick:function(){
    this.navigateToDetailSongsPage("hotRanking")
  },

  handleRankingItemClick:function(event){
    const idx = event.currentTarget.dataset.idx
   const ranking = rankingMap[idx]
    this.navigateToDetailSongsPage(ranking)
  },

  navigateToDetailSongsPage:function(rankingName){
    wx.navigateTo({
      url:`../detail-songs/index?ranking=${rankingName}&type=rank`
    })
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  getRankingHandle:function(idx){
   return (res)=>{
    if(!res.tracks) return
    // console.log("idx:",idx);
    const name = res.name
    const coverImgUrl = res.coverImgUrl
    const playCount = res.playCount
    const songList = res.tracks.slice(0,3)
    const rankingObj = {name,coverImgUrl,playCount,songList}
    const newRankings = {...this.data.rankings,[idx]: rankingObj}
    // newRankings.push(rankingObj)
    this.setData({
      rankings:newRankings
    })
    // console.log(this.data.rankings)
   }
  }

})